{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 [0.052566912, 0.09935848]\n",
      "21 [0.102278665, 0.19878922]\n",
      "41 [0.101102605, 0.19941418]\n",
      "61 [0.10053353, 0.19971652]\n",
      "81 [0.100258164, 0.19986284]\n",
      "101 [0.10012492, 0.19993363]\n",
      "121 [0.10006043, 0.19996789]\n",
      "141 [0.10002924, 0.19998446]\n",
      "161 [0.10001414, 0.1999925]\n",
      "181 [0.10000684, 0.19999637]\n",
      "201 [0.1000033, 0.19999824]\n"
     ]
    }
   ],
   "source": [
    "# 生成随机点\n",
    "x_data = np.random.rand(100)\n",
    "y_data = x_data*0.1 + 0.2\n",
    "\n",
    "# 构建线性模型\n",
    "b = tf.Variable(0.)\n",
    "k = tf.Variable(0.)\n",
    "y = k*x_data + b\n",
    "\n",
    "# 定义损失函数\n",
    "loss = tf.reduce_mean(tf.square(y_data-y))\n",
    "# 定义一个梯度下降法进行训练的优化器,学习率是0.2\n",
    "optimizer = tf.train.GradientDescentOptimizer(0.2)\n",
    "# 最小化代价函数\n",
    "train = optimizer.minimize(loss)\n",
    "\n",
    "# 变量初始化\n",
    "init = tf.global_variables_initializer()\n",
    "\n",
    "with tf.Session() as sess:\n",
    "    sess.run(init)\n",
    "    for step in range(201):\n",
    "        sess.run(train)\n",
    "        if step%20 == 0:\n",
    "            print(step+1, sess.run([k,b]))\n",
    "        \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
